<script >
import { ref, onMounted, computed, watch } from "vue";
import { Draw } from "../../components/Draw";
import { nanoid } from "nanoid";
// import CreatePlist from "../../../components/create-plist.vue";
// import RectModify from "../../../components/rect-modify.vue";
import CreateImage from "../../components/editor/CreateImage.vue";
import CreateRect from "../../components/editor/CreateRect.vue";
import { readFile, dataURL2Image } from "../../utils"; 
import {PlistReader} from "../../utils/PlistReader"
import {Graph} from '../../components/Graph'

const IMG_DATAS = "img-datas";
const PLIST = "plist";
let currentImage = null;
let draw = null;
let gridDraw = null;
function strogeSaved(key, data) {
  localStorage.setItem(key, JSON.stringify(data));
}

export default {
  components: {
    CreateImage,
    CreateRect,
  },
  data() {
    return {
      plistText:'',
      currentRect: {},
      visible: false,
      rectVisible: false,
      plistSelected: {},
      editor: {},
      plistArray: [],
      formData: {
        fileName: "",
      },
    };
  },

  setup() {},
  mounted() {
    let plist = localStorage.getItem(PLIST);
    let imgDatas = localStorage.getItem(IMG_DATAS);



    if (imgDatas) {
      imgDatas = JSON.parse(imgDatas);

      let _ = this;
      const image = new Image();

      image.src = imgDatas.image;

      image.onload = function () {
        imgDatas.image = image;
        _.onplistSaved(imgDatas, "loaded");
        if (plist) {
          plist = JSON.parse(plist);

          _.plistArray = plist;
        }
      };

  
    }
  },

  methods: {
    async onReadFile() {
      let result = await readFile("text");
      this.plistText = result.data

      let reader = PlistReader.reader2Text(result.data).toPlistRes()
      this.plistArray = reader.list.map((v)=>{
        const url = draw.getImageData(v.frame);

        return {
          ...v,
          url:url
        }
      })
      strogeSaved(PLIST, this.plistArray);
    },


    onBatchDelete() {
      Object.keys(this.plistSelected).forEach((v) => {
        if (this.plistSelected[v]) {
          this.onRectDelete({ id: v });
        }
      });
    },
    onCheckSlected(item) {
      let id = item.id;

      this.plistSelected = {
        ...this.plistSelected,
        [id]: !this.plistSelected[id],
      };
    },
    async onCreateSplit() {
      // this.editor = {};
      // this.visible = true;

      let result = await readFile();
      let image = await dataURL2Image(result.data);


      this.onplistSaved({
        fileName: result.fileName,
        image: image,
        size: 16,
        space: 0,
      });
    },
    onplistSaved(data, type) {
      let _ = this;
      this.editor = data;
      console.log(data);

      strogeSaved(IMG_DATAS, {
        ...data,
        editor: false,
        image: data.image.src,
      });
      // console.log(data.image.src)

      if (!type) {
        this.plistArray = [];
        strogeSaved(PLIST, this.plistArray);
      }

      currentImage = data.image;

      this.formData.fileName = data.fileName;

      if (!data.editor) {
        draw = Draw.createCanvas({
          width: data.image.width,
          height: data.image.height,
          el: "editor-content",
          canvasName: "back-graph",
        });

        // console.log(data)
        // draw.clear()
        draw.drawImage(data.image);
      }

      //  let datas= draw.getImageDatas(16,19,1,1)
      // console.log(datas)

      // let gNode = Graph.setGraphByImageData(draw.getImageDatas(),data.image.width,data.image.height);
      //  console.log(gNode)
       gridDraw = Draw.createCanvas({
        width: data.image.width,
        height: data.image.height,
        el: "editor-content",
        canvasName: "back-graph-grid",
      });
      
      // gNode.drawGrid(gridDraw)

      
      gridDraw.drawGrid({
        size: data.size,
        space: data.space,
      });

      gridDraw.on("click", function (e) {
        // console.log(e.clientX, e.clientY);

        // _.mouseToCanvas({x:e.clientX,y:e.clientY})
        let pos = gridDraw.mouseToCanvas({ x: e.clientX, y: e.clientY });

        let frame = {
          x: pos.x - (pos.x % data.size),
          y: pos.y - (pos.y % data.size),
          w: data.size,
          h: data.size,
        };

        const url = draw.getImageData(frame);

        _.plistArray.push({
          id: nanoid(),
          key: _.plistArray.length + 1 + ".png",
          url: url,
          frame: frame,
          offset: { x: 0, y: 0 },
          rotated: false,
          sourceColorRect: { x: 0, y: 0, w: data.size, h: data.size },
          sourceSize: { w: data.size, h: data.size },
        });

        strogeSaved(PLIST, _.plistArray);
      });
    },
    onSelectRect(data) {
      // this.rectVisible = true;
      this.editor = { ...data.frame, key: data.key, id: data.id };

      this.currentRect = data;
    },
    onRectModify(data) {
      let idx = this.plistArray.findIndex((v) => v.id === data.id);

      const w = parseInt(data.w);
      const h = parseInt(data.h);

      const x = parseInt(data.x);
      const y = parseInt(data.y);
      data.w = w;
      data.h = h;
      data.x = x;
      data.y = y;

      if (data.created) {
        const url = draw.getImageData({
          x: x,
          y: y,
          w: w,
          h: h,
        });

        this.plistArray.push({
          id: nanoid(),
          key: data.key.replace("${number}", Math.floor(x / w)),
          frame: { x: x, y: y, w: w, h: h },
          offset: { x: 0, y: 0 },
          url: url,
          rotated: false,
          sourceColorRect: { x: 0, y: 0, w: w, h: h },
          sourceSize: { w: w, h: h },
        });
        strogeSaved(PLIST, this.plistArray);
        return;
      }

      if (idx != -1) {
        const item = this.plistArray[idx];

        const url = draw.getImageData({
          x: x,
          y: y,
          w: w,
          h: h,
        });
        this.plistArray.splice(idx, 1, {
          id: item.id,
          key: data.key.replace("${number}", Math.floor(x / w)),
          frame: { x: x, y: y, w: w, h: h },
          offset: { x: 0, y: 0 },
          url: url,
          rotated: false,
          sourceColorRect: { x: 0, y: 0, w: w, h: h },
          sourceSize: { w: w, h: h },
        });
        strogeSaved(PLIST, this.plistArray);
      }

      if (data.batchSet) {
        this.batchRectSet(data);
      }
    },
    onRectDelete(data) {
      let idx = this.plistArray.findIndex((v) => v.id === data.id);
      if (idx != -1) {
        this.plistArray.splice(idx, 1);
      }
      strogeSaved(PLIST, this.plistArray);
    },

    batchRectSet(data) {
      const offsetX = parseInt(data.offestX);
      const offsetY = parseInt(data.offestY);

      for (let i = data.x + offsetX; i < gridDraw.canvas.width; i += offsetX) {
        data.x = i;
        this.onRectModify({
          ...data,
          batchSet: false,
          created: true,
        });
      }
    },
    onCancelRect() {
      this.onRectModify({
        ...this.currentRect.frame,
        key: this.currentRect.key,
        id: this.currentRect.id,
      });

      let item = this.plistArray.find((v) => v.id === this.currentRect.id);

      if (item) {
        this.currentRect.url = item.url;
      }
    },

    onGenerate() {
      let frameData = [];

      this.plistArray.forEach((plist) => {
        let keyItem = `
  <key>${plist.key}</key>
  <dict>
    <key>frame</key>
                <string>{{${plist.frame.x},${plist.frame.y}},{${plist.frame.w},${plist.frame.h}}}</string>
                <key>offset</key>
                <string>{${plist.offset.x},${plist.offset.y}}</string>
                <key>rotated</key>
                <false/>
                <key>sourceColorRect</key>
                <string>{{${plist.sourceColorRect.x},${plist.sourceColorRect.y}},{${plist.sourceColorRect.w},${plist.sourceColorRect.h}}}</string>
                <key>sourceSize</key>
                <string>{${plist.sourceSize.w},${plist.sourceSize.h}}</string>
  </dict>
  `;
        frameData.push(keyItem);
      });

      let size = `{${currentImage.width},${currentImage.height}}`;

      const fileName = this.formData.fileName;

      let template = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>frames</key>
<dict>
  ${frameData.join("")}
</dict>
<key>metadata</key>
<dict>
<key>format</key>
<integer>2</integer>
<key>realTextureFileName</key>
<string>${fileName}</string>
<key>size</key>
<string>${size}</string>
<key>textureFileName</key>
<string>${fileName}</string>
</dict>
</dict>
</plist>`;

      // console.log(template);

      var a = document.getElementById("generate-file");

      var file = new Blob([template], { type: "text/plain" });
      a.href = URL.createObjectURL(file);

      const newName = fileName.split(".");

      a.download = newName[0] + ".plist";
      a.dispatchEvent(
        new MouseEvent("click", { bubbles: false, cancelable: true })
      );
    },
  },
};
</script>

<template>
  <div class="plist-editor">
    <div class="editor-toolbar">
      <div class="toolbar toolbar-left" style="margin-right:20px">
        <el-button type="primary" @click="onCreateSplit">创建</el-button>
      </div>
      <div class="toolbar toolbar-right"></div>
     
    </div>
    <div class="editor-content" id="editor-content">
      <div class="rect-items">
        <div
          class="rect"
          v-for="(item, key) in plistArray"
          :key="key"
          @click="onSelectRect(item)"
          :style="{
            top: item.frame.y + 'px',
            left: item.frame.x + 'px',
            width: item.frame.w + 'px',
            height: item.frame.h + 'px',
          }"
        ></div>
      </div>
    </div>
    <div class="editor-footer">
      <div class="left">
        <div class="add-layer">
          <div>
            <el-input
              size="small"
              v-model="formData.fileName"
              placeholder="文件名"
            />
          </div>
          <el-button type="primary" size="small" @click="onReadFile"
            >读取</el-button
          >
          <el-button type="primary" size="small" @click="onGenerate"
            >生成</el-button
          >
          <el-button type="primary" size="small" @click="onBatchDelete"
            >批量删除</el-button
          >
          <a id="generate-file" style="display: none" href=""></a>
        </div>
        <div>
          <div
            class="item"
            v-for="(item, key) in plistArray"
            :key="key"
            @click="onSelectRect(item)"
            :style="{
              'font-size': 0,
            }"
          >
            <el-checkbox
              :value="plistSelected[item.id]"
              @click.stop="() => {}"
              @change="onCheckSlected(item)"
            />
            <el-image
              style="width: 30px; height: 30px"
              :src="item.url"
              fit="scale-down"
            />
            <span class="label">{{ item.key }}</span>

            <el-button size="small" :link="true" @click.stop="onRectDelete(item)"
              >删除</el-button
            >
          </div>
        </div>
      </div>
      <div class="right protery" style="margin-right: 20px">
        <div v-if="currentRect.url">
          <img :src="currentRect.url" alt="" />
        </div>
        <div v-if="currentRect.url">
          <el-form
            label-width="100px"
            :model="currentRect"
            style="max-width: 460px"
          >
            <el-form-item label="key">
              <el-input
                v-model="currentRect.key"
                size="small"
                @input="onCancelRect"
              />
            </el-form-item>
            <el-form-item label="x">
              <el-input
                v-model="currentRect.frame.x"
                size="small"
                @input="onCancelRect"
              />
            </el-form-item>
            <el-form-item label="y">
              <el-input
                v-model="currentRect.frame.y"
                size="small"
                @input="onCancelRect"
              />
            </el-form-item>
            <el-form-item label="w">
              <el-input
                v-model="currentRect.frame.w"
                size="small"
                @input="onCancelRect"
              />
            </el-form-item>
            <el-form-item label="h">
              <el-input
                v-model="currentRect.frame.h"
                size="small"
                @input="onCancelRect"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="right"></div>
      
    </div>
  </div>
  <CreateImage v-model:visible="visible" :data="editor" @saved="onplistSaved" />

  <CreateRect
    v-model:visible="rectVisible"
    :data="editor"
    @saved="onRectModify"
    @delete="onRectDelete"
  />
</template>

<style lang="scss">
.plist-editor {
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .editor-toolbar {
    height: 64px;
    margin: 20px;
    // background-color: #fff;
    display: flex;
    .toolbar{
      background-color: #fff;
      height: 100%;
      border-radius: 10px;
      box-sizing: border-box;
 

    }
    .toolbar-left{
      width: 420px;
      display: flex;
      align-items: center;
      padding: 20px;
    }
    .toolbar-right{
      flex-grow: 1;
    }
  }
  .editor-content {
    background-color: rgba(0, 0, 0, 0.6);
    flex-grow: 1;
    overflow: auto;
    margin: 0 20px;
    height: 585px;
    position: relative;
  }

  .editor-footer {
    margin: 20px;
    height: 240px;
    // background-color: #fff;
    display: flex;
    .left {
      width: 320px;
      height: 100%;
      background-color: #fff;
      border-radius: 6px;
      margin-right: 20px;

      box-sizing: border-box;
      overflow: hidden;
      overflow-y: auto;
      .add-layer {
        display: flex;
        justify-content: space-between;
        position: sticky;
        top: 0;
        z-index: 100;
        background-color: #fff;
        padding: 10px;
      }

      .item {
        display: flex;
        align-items: center;
        padding: 0 10px;
        .label {
          font-size: 12px;
          line-height: 12px;
          margin-left: 10px;
        }
      }
    }
    .right {
      flex-grow: 1;
      height: 100%;
      background-color: #fff;
      border-radius: 6px;
      overflow: hidden;
      padding: 10px;
      box-sizing: border-box;
      overflow: hidden;
      overflow-y: auto;
      max-width: 760px;
    }
    .protery {
      display: flex;
    }
  }
  .graph-canvas {
    position: absolute;
    top: 0;
    left: 0;
  }
  .rect-items {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1500;
    .rect {
      position: absolute;
      z-index: 1501;
      // top: 12px;
      // left: 12px;
      // width: 16px;
      // height: 16px;
      background-color: blue;
      opacity: 0.5;
    }
  }
}
</style>
